package edu.yuhf.web.servlet;

import com.alibaba.fastjson.JSON;

import edu.yuhf.domain.User;
import edu.yuhf.service.UserServiceImpl;
import edu.yuhf.service.iface.UserService;
import edu.yuhf.utils.WebUtils;
import lombok.extern.log4j.Log4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
@Log4j
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserService userService = new UserServiceImpl();

        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        String[] params = WebUtils.getPath(req);
        //准备响应式输出流
        PrintWriter out = resp.getWriter();      //out是前端输出数据的对象
        Map<String, Object> map = new HashMap(); //数据容器

        //转向不同的业务处理单元（Service）
        switch (params[1]) {
            case "queryAll":
                List<User> list = userService.queryUserAll();
                map.put("users", list);
                map.put("result", "ok");
                break;
            case "login": {
                if (userService.queryUserByNameAndPwd(userName, password)){
                    map.put("result","ok");
                }else{
                    map.put("result","error");
                    map.put("message","用户名或密码错误！");
                }
                break;
            }
        }
        String jsonString = JSON.toJSONString(map); //利用fastjson包，将java对象转换成json字符串
        out.println(jsonString);       //将json字符串，发送给前端
        out.flush();                   //刷新缓冲区
        out.close();                   //关闭输出流
    }
}
